import type { MaybeRefOrGetter } from 'vue'
import type { IndicatorInfo } from '@/types'
import { dataManagementApi } from '@/api'

export interface ModelConfig {
  modelType: string
  indicatorIds: number[]
  pointId?: number
}

export const IS_BINDING = 1
export const IS_UNBINDING = 2

export enum PERIODS {
  HOUR,
  DATE,
  MONTH,
  YEAR,
}

export function useModelConfigs() {
  const [operateType, setOperateType] = useState(0)
  const [checkedList, setCheckedList] = useShallowState<
    IndicatorInfo[]
  >([])

  const isBinding = computed(() => {
    return operateType.value === IS_BINDING
  })
  const isUnbinding = computed(() => {
    return operateType.value === IS_UNBINDING
  })
  const showCheckbox = computed(() => {
    return operateType.value > 0
  })
  const saveText = computed(() => {
    if (isBinding.value)
      return '确认绑定'
    if (isUnbinding.value)
      return '确认解绑'
    return ''
  })
  const saveButtonType = computed(() => {
    if (isBinding.value)
      return 'success'
    if (isUnbinding.value)
      return 'danger'
    return 'default'
  })

  async function clickBind(modelType: string) {
    const checked = toValue(checkedList)
    const indicatorIds = checked.map((v: any) => v.id)
    if (indicatorIds.length > 0) {
      const pointId = checked[0]?.pointId
      if (pointId) {
        try {
          await modelConfigApi.addModelConfig({
            modelType,
            indicatorIds,
            pointId,
          })
          ElMessage.success('绑定成功')
        }
        catch (e) {
          ElMessage.error('绑定失败')
        }
      }
      else {
        console.warn('pointId: ', pointId)
        ElMessage.error('绑定应用模型异常')
      }
    }
    else {
      ElMessage.error('请勾选指标绑定应用模型')
    }
  }

  async function clickUnbind(modelType: string) {
    const checked = toValue(checkedList)
    const indicatorIds = checked.map((v: any) => v.id)
    try {
      await modelConfigApi.updateModelConfig({
        modelType,
        indicatorIds,
      })
      ElMessage.success('解绑成功')
    }
    catch (e) {
      ElMessage.error('解绑失败')
    }
  }

  return {
    operateType,
    isBinding,
    isUnbinding,
    showCheckbox,
    checkedList,
    saveText,
    saveButtonType,

    setOperateType,
    setCheckedList,
    clickBind,
    clickUnbind,
  }
}

export function useIndicatorDataCurve(
  query: MaybeRefOrGetter<any>,
) {
  const loading = ref(false)
  const visible = ref(false)
  const pageHeaderTitle = ref('')
  const lineOption = computed(() => {
    return {
      legend: {
        show: false,
      },
      toolbox: {
        show: true,
        feature: {
          dataZoom: {
            yAxisIndex: 'none',
            title: {
              zoom: '区域缩放',
              back: '区域缩放还原',
            },
          },
          dataView: { readOnly: false, title: '数据视图' },
          magicType: {
            type: ['line', 'bar'],
            title: {
              line: '切换为折线图',
              bar: '切换为柱状图',
            },
          },
          restore: {
            title: '还原',
          },
          saveAsImage: {
            title: '保存为图片',
          },
        },
      },
      // dataZoom: [
      //   { type: 'slider', start: 0, end: 50 },
      //   { type: 'inside', start: 0, end: 50 }
      // ]
    }
  })
  const indicator = ref({
    indicatorName: '',
    indicatorCode: '',
    dataTime: '',
  })
  const indicatorData = ref([])
  const lineDataset = computed(() => {
    const data = indicatorData.value as {
      dataTime: string
      val: number
    }[]
    return {
      source: [
        data.map(v => v.dataTime),
        data.map(v => v.val),
      ],
    }
  })

  const requestIndicatorData = computed(() => {
    const { period } = toValue(query)
    const {
      loadDayResourceListByIndicator,
      loadHourResourceListByIndicator,
      loadMonthResourceListByIndicator,
    } = dataManagementApi
    let rq = null
    switch (period) {
      case PERIODS.DATE:
        rq = loadHourResourceListByIndicator
        break
      case PERIODS.MONTH:
        rq = loadDayResourceListByIndicator
        break
      case PERIODS.YEAR:
        rq = loadMonthResourceListByIndicator
        break
    }
    return rq
  })

  const getIndicatorData = async () => {
    loading.value = true
    const { indicatorCode, dataTime } = indicator.value
    try {
      const { data } = await requestIndicatorData.value!(
        indicatorCode,
        dataTime,
      )
      if (data) {
        indicatorData.value = data.map((v: any) => {
          return {
            dataTime: v.dataTime,
            val: v.val,
          }
        })
      }
    }
    finally {
      loading.value = false
    }
  }

  return {
    visible,
    pageHeaderTitle,
    lineOption,
    indicator,
    indicatorData,
    lineDataset,
    requestIndicatorData,
    getIndicatorData,
  }
}
